<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getSysAuthorityRoute, addSysAuthorityRoute, delSysAuthorityRoute, getRouterList } from "@/api/sysRole"

import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { treeArr } from "@/utils/index"

defineOptions({
  // 命名当前组件
  name: "sysRole"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  roleName: "",
  pid: "",
  powerIds: ""
})
const formRules: FormRules = reactive({
  roleName: [{ required: true, trigger: "blur", message: "请输入角色名" }]
  // path: [{ required: true, trigger: "blur", message: "请输入密码" }]
})
const handleCreate = () => {
  // console.log(  treeqx.value.getCheckedNodes(),'handleCreate' )
  // return
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      let powerIdsArr = treeqx.value.getCheckedNodes().map((it) => {
        return it.id
      })
      if (currentUpdateId.value === undefined) {
        addSysAuthorityRoute({
          ...formData,
          powerIds: powerIdsArr.join(",")
        })
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        addSysAuthorityRoute({
          id: currentUpdateId.value,
          ...formData,
          powerIds: powerIdsArr.join(",")
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
// 重置数据
const resetForm = () => {
  currentUpdateId.value = undefined
  // formData.roleName = ""
  // formData.pid = ""
  // formData.powerIds = ""
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`正在删除角色：${row.roleName}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delSysAuthorityRoute([row.id]).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  currentUpdateId.value = row.id
  formData.roleName = row.roleName
  formData.pid = row.pid
  formData.powerIds = row.powerIds
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<any[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  roleName: "",
  id: ""
})
// 获取列表数据
const getTableData = () => {
  console.log(getTableData)

  loading.value = true
  getSysAuthorityRoute({
    page: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.roleName || undefined,
    id: searchData.id || undefined
  })
    .then((res) => {
      paginationData.total = res.data.total
      console.log(res)
      tableData.value = res.data.records
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

/** 设置树状权限列表 */

const defaultProps = {
  children: "children",
  label: "name"
}
const treedata = ref([])
// 获取所有列表路由
const GetAllList = () => {
  getRouterList({}).then((res) => {
    let data = res.data
    // console.log(treeArr(data) );

    treedata.value = treeArr(data)
  })
}
GetAllList()

let treeqx = ref()
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="roleName" label="角色名">
          <el-input v-model="searchData.roleName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="id" label="角色id">
          <el-input v-model="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增角色</el-button>
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="id" align="center" />
          <el-table-column prop="roleName" label="角色名字" align="center" />
          <el-table-column prop="pid" label="父级ID" align="center" />
          <el-table-column prop="powerIds" label="权限节点" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增角色' : '修改角色'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="roleName" label="角色名字">
          <el-input v-model="formData.roleName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="pid" label="父级ID">
          <el-input v-model="formData.pid" placeholder="" />
        </el-form-item>
        <el-form-item prop="powerIds" label="权限节点">
          <el-tree
            :data="treedata"
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :default-expanded-keys="[]"
            :default-checked-keys="[]"
            :props="defaultProps"
            ref="treeqx"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
